package com.itheima.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mall.exception.BusinessException;
import com.itheima.mall.exception.ErrorResult;
import com.itheima.mall.mapper.HomeBrandMapper;
import com.itheima.mall.pojo.HomeBrand;
import com.itheima.mall.service.SmsHomeBrandService;
import com.itheima.mall.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SmsHomeBrandServiceImpl extends ServiceImpl<HomeBrandMapper, HomeBrand> implements SmsHomeBrandService {

    @Autowired
    private HomeBrandMapper homeBrandMapper;

    /**
     * 分页查询推荐品牌
     */
    @Override
    public PageResult getList(String brandName, Integer pageNum, Integer pageSize, Integer recommendStatus) {
        Page<HomeBrand> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<HomeBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(brandName != null,HomeBrand::getBrandName,brandName)
                .eq(recommendStatus != null,HomeBrand::getRecommendStatus,recommendStatus)
                .orderByAsc(HomeBrand::getSort);
        Page<HomeBrand> pageInfo = homeBrandMapper.selectPage(page, queryWrapper);
        return new PageResult(pageNum,pageSize, (int) pageInfo.getTotal(),pageInfo.getRecords());
    }

    /**
     * 添加首页推荐品牌
     */
    @Override
    public void createBrand(List<HomeBrand> homeBrandList) {
        if (CollUtil.isEmpty(homeBrandList)){
            throw new BusinessException(ErrorResult.error());
        }
        this.saveBatch(homeBrandList);
    }

    /**
     * 批量删除推荐品牌
     */
    @Override
    public void deleteBrand(List<Long> ids) {
        if (CollUtil.isEmpty(ids)){
            throw new BusinessException(ErrorResult.error());
        }
        this.removeBatchByIds(ids);
    }

    /**
     * 批量修改推荐品牌状态
     */
    @Override
    public void updateBrand(List<Long> ids, Integer recommendStatus) {
        LambdaUpdateWrapper<HomeBrand> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(HomeBrand::getRecommendStatus,recommendStatus);
        updateWrapper.in(HomeBrand::getId,ids);
        homeBrandMapper.update(null,updateWrapper);
    }

    /**
     * 修改推荐品牌排序
     */
    @Override
    public void updateSort(Long id, Integer sort) {
        LambdaUpdateWrapper<HomeBrand> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(sort != null,HomeBrand::getSort,sort);
        updateWrapper.eq(id != null ,HomeBrand::getId,id);
        homeBrandMapper.update(null,updateWrapper);
    }


}
